package allwe.thread08;

import java.util.concurrent.DelayQueue;

public class Test {
    DelayQueue<User> a = new DelayQueue<>();

    public static void main(String[] args) {
        Test queue = new Test();
        //添加用户
        User user1 = new User(1,"张三",System.currentTimeMillis() + 5000);
        User user2 = new User(1,"李四",System.currentTimeMillis() + 10000);
        User user3 = new User(1,"拉拉",System.currentTimeMillis() + 2000);

        queue.login(user1);
        queue.login(user2);
        queue.login(user3);

        //一直监控
        while (true){
            //到期的话，就自动下线
            queue.logout();
            // 如果都下线了，就停止监控
            if (queue.onlineSize() == 0)
                break;
        }
    }

    public void login(User user){
        a.add(user);
        System.out.println("用户：[" + user.getId() + "],[" + user.getName() + "]已经登录，预计下机时间为：" + user.getEndTime());

    }

    public void logout(){
        System.out.println(a);
        try {
            User user = a.take();
            System.out.println("用户：[" + user.getId() + "],[" + user.getName() + "]已经下机");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    //在线人数
    public int onlineSize(){
        return a.size();
    }
}
